﻿using Singer.Shared.UserContext;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;

namespace Singer.Middleware.JwtAuth;

public static class TokenExtensions
{
    /// <summary>
    /// 读取JwtToken中的有效载荷
    /// </summary>
    public static ClaimsPrincipal? ReadJwtTokenAsClaims(string token)
    {
        if (string.IsNullOrWhiteSpace(token))
            return null;
        JwtSecurityToken securityToken = new JwtSecurityToken(token);
        var claimsIdentity = new ClaimsIdentity(securityToken.Claims) ?? new ClaimsIdentity();
        var claimsPrincipal = new ClaimsPrincipal(claimsIdentity) ?? new ClaimsPrincipal();
        return claimsPrincipal;
    }

    /// <summary>
    /// 读取JwtToken中的有效载荷
    /// </summary>
    public static IUserContext? ReadJwtTokenAsUserContext(string token)
    {
        ClaimsPrincipal? claimsPrincipal = ReadJwtTokenAsClaims(token);
        IUserContext? userContext = ReadClaimsAsUserContext(claimsPrincipal);
        return userContext;
    }

    /// <summary>
    /// 将有效载荷读取为用户信息上下文
    /// </summary>
    public static IUserContext? ReadClaimsAsUserContext(ClaimsPrincipal? claimsPrincipal)
    {
        if (claimsPrincipal == null)
            return null;
        IUserContext userContext = new DefaultUserContext
        {
            TenantId = claimsPrincipal?.Claims?.FirstOrDefault(x => x.Type == nameof(IUserContext.TenantId))?.Value ?? "",
            TenantCode = claimsPrincipal?.Claims?.FirstOrDefault(x => x.Type == nameof(IUserContext.TenantCode))?.Value ?? "",
            TenantName = claimsPrincipal?.Claims?.FirstOrDefault(x => x.Type == nameof(IUserContext.TenantName))?.Value ?? "",
            UserId = claimsPrincipal?.Claims?.FirstOrDefault(x => x.Type == nameof(IUserContext.UserId))?.Value ?? "",
            UserName = claimsPrincipal?.Claims?.FirstOrDefault(x => x.Type == nameof(IUserContext.UserName))?.Value ?? "",
            Mobile = claimsPrincipal?.Claims?.FirstOrDefault(x => x.Type == nameof(IUserContext.Mobile))?.Value ?? "",
        };
        return userContext;
    }
}
